﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Extensions
{
	using System;
	using System.Collections.Generic;
	using Falcon.Core.Collections;

	public static class EnumerableExtension
	{
		/// <summary>
		/// Enumerates the list using the specified action.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="values">The values.</param>
		/// <param name="action">The action.</param>
		public static void ForEach<T>(this IEnumerable<T> values, Action<T> action)
		{
			if (values == null)
			{
				return;
			}

			foreach (var value in values)
			{
				action(value);
			}
		}

		/// <summary>
		/// Determines whether the specified list has values.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="values">The values.</param>
		/// <returns>
		/// 	<c>true</c> if the specified values has value; otherwise, <c>false</c>.
		/// </returns>
		public static bool HasValue<T>(this IList<T> values)
		{
			return (values != null && values.Count > 0);
		}

		/// <summary>
		/// Gets the first item in the list or the default when the list is empty.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="values">The values.</param>
		/// <returns></returns>
		public static T FirstOrDefault<T>(this IList<T> values) where T : new()
		{
			return values.HasValue() ? values[0] : new T();
		}

		/// <summary>
		/// Gets the first item in the list or the default when the list is empty.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <typeparam name="TK"></typeparam>
		/// <param name="values">The values.</param>
		/// <returns></returns>
		public static T FirstOrDefault<T, TK>(this IPagedList<T, TK> values) where T : new()
		{
			return values.Items.HasValue() ? values.Items[0] : new T();
		}
	}
}